package cn.edu.sdjzu.xg23.kcsj01_backend.service.impl;


import cn.edu.sdjzu.xg23.kcsj01_backend.entity.User;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.authority.Role;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.authority.UserAssRole;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.UserAssRoleMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.UserMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.UserService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.Result;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.SnowflakeIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserAssRoleMapper userAssRoleMapper;

    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;

    @Transactional
    @Override
    public boolean addUser(User user, List<Long> roleIds) {
        try {
            // 1. 生成ID并保存用户
            Long userId = snowflakeIdGenerator.generateId();
            user.setId(userId);
            int rows = userMapper.addUser(user); // 返回插入的行数

            // 2. 检查用户插入是否成功
            if (rows <= 0) {
                return false;
            }

            // 3. 构建并插入角色关联
            if (roleIds != null && !roleIds.isEmpty()) {
                List<UserAssRole> associations = roleIds.stream()
                        .map(roleId -> {
                            UserAssRole assoc = new UserAssRole();
                            assoc.setUser(new User(userId)); // 正确设置用户对象
                            assoc.setRole(new Role(roleId));
                            return assoc;
                        })
                        .collect(Collectors.toList());

                userAssRoleMapper.insertBatch(associations);
            }else if (roleIds.size() == 0){
                return false;
            }

            return true;
        } catch (Exception e) {
            Result.error("添加用户失败", e.getMessage());
            return false;
        }
    }


    @Override
    public User loginWithRole(String username, String password, Long roleId) {
        User user = userMapper.selectByUsernameAndPassword(username, password);
        if (user == null) {
            return null;
        }else {
            userMapper.updateLoginTime(user.getId());
        }

        // 2. 校验用户是否拥有该角色
        boolean hasRole = userAssRoleMapper.existsByUserIdAndRoleId(user.getId(), roleId);
        if (!hasRole) {
            return null; // 角色不属于该用户
        }

        return user;
    }

    @Override
    public PageInfo<User> selectUser(Integer pageNum, Integer pageSize, User user) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.selectUser(user);
        return new PageInfo<>(userList);
    }

    @Override
    public boolean deleteUser(Long id) {
        return userMapper.deleteUser(id);
    }

    @Override
    public boolean resetPassword(Long id) {
        return userMapper.resetPassword(id);
    }

    @Override
    public boolean updatePassword(User user, String oldPassword) {
        String selectedPassword  = userMapper.selectPasswordById(user.getId());
        if (selectedPassword.equals(oldPassword)) {
            return userMapper.updatePassword(user);
        } else {
            return false;
        }
    }
}
